import axios from 'axios'

axios.defaults.timeout = 1000 * 5 //超市时间是30秒
axios.defaults.withCredentials = true  //允许跨域
//Content-Type 响应头
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
//基础url
axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? 'http://121.89.172.98:8888' : 'http://localhost:8888'

//响应拦截器
axios.interceptors.response.use(
    response => {
        console.log(response)
        //如果reponse里面的status是200，说明访问到接口了，否则错误
        if (response.data && response.status === 200) {
            return Promise.resolve(response)
        } else {
            return Promise.reject(response)
        }
    },
    error => {
        return Promise.reject(error)
    }
)

/**
 * 封装get方法
 * @param url 请求地址
 * @param params 参数
 * @returns {Promise<unknown>}  异步对象
 */
export function get(url, params = {}) {
    return new Promise((resolve, reject) => {
        axios.get(url, {params: params}).then(response => {
            resolve(response)
        }).catch(err => {
            reject(err)
        })
    })
}

/**
 * 封装post方法
 * @param url 请求地址
 * @param data
 * @returns {Promise<unknown>}  异步对象
 */
export function post(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.post(url, data).then(response => {
            resolve(response)
        }).catch(err => {
            reject(err)
        })
    })
}